// pages/address_list/index.js
import { getAddressList, updateAddress } from '../../api/index'
import { objectToSearh } from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    checked: '',
    show: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { id } = options
    if (!this.data.show) {
      this.setData({ checked: Number(id), show: true }, () => {
        this.getList()
      })
    }
  },
  onShow() {
    if (this.data.show) {
      this.getList()
    }
  },
  // 获取地址列表
  getList() {
    getAddressList().then(res => {
      const { result = [] } = res.data
      const defOne = result.filter(v => v.isDefault === true)
      const checkOne = result.filter(v => v.id === this.data.checked)
      // 存在默认-选择默认
      if (defOne.length > 0) {
        this.setData({ checked: defOne[0].id, list: result })
      } else if (checkOne.length === 0) {
        // 传入id在列表中查询不到-默认列表第一项
        this.setData({ checked: result[0].id, list: result })
      } else {
        this.setData({ list: result })
      }
    })
  },
  // 修改收货地址-选中改为默认
  defAddress(e) {
    const { item = {} } = e.target.dataset
    const params = {
      ...item,
      isDefault: true
    }
    this.setData({ checked: item.id })
    updateAddress(params).then(res => {
      // wx.switchTab({
      //   url: '/pages/cart/index',
      // });
      wx.navigateBack({
        delta: 1
      });
        
    })
  },
  // 跳转收货地址详情
  goAddress(e) {
    const { item = {} } = e.target.dataset
    wx.navigateTo({
      url: '/pages/address/index' + objectToSearh({ item }),
    });
  }
})